package com.blazhovsky.mk.androidlan;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import android.os.AsyncTask;

public class NitkaZaPrakjanje
{
	MainActivity context;
	String porakaStoKeSePrakja;

	DataOutputStream dataOutputStreamZaPrakjanje = null;
	Socket socketZaPrakjanje = null;

	public NitkaZaPrakjanje(MainActivity c, String porakaZaPrakjanje)
	{
		context = c;
		porakaStoKeSePrakja = porakaZaPrakjanje;
	}

	public void pocni()
	{
		new MyAsyncTaskPrakjanje().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
	}

	private class MyAsyncTaskPrakjanje extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params)
		{
			context.klientIP = context.adresaZaPrakjanje.getText().toString();
			if (context.klientIP != "")
			{
				try
				{
					System.out.println("prakam na: " + context.klientIP);
					socketZaPrakjanje = new Socket(context.klientIP, 8888);
					dataOutputStreamZaPrakjanje = new DataOutputStream(socketZaPrakjanje.getOutputStream());

					dataOutputStreamZaPrakjanje.writeUTF(porakaStoKeSePrakja);
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finally
				{
					if (socketZaPrakjanje != null)
					{
						try
						{
							socketZaPrakjanje.close();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					if (dataOutputStreamZaPrakjanje != null)
					{
						try
						{
							dataOutputStreamZaPrakjanje.close();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				System.out.println("Zavrsi prakjanjeto");
			}
			else porakaStoKeSePrakja = "SELEKTIRAJTE ADRESA ZA PRAKJANJE!";

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			context.refresh("Me: " + porakaStoKeSePrakja + "\n");
		}
	}
}
